---
created:
source_filename: /home/runner/work/mknodes/mknodes/mknodes/pages/mkclasspage/__init__.py
source_function: MkClassPage.__init__
source_line_no: 46
hide:
- toc
icon: octicons/link-24
template: SUMMARY.html
title: MkLink
---
[:fa-brands-github: Show source on GitHub](https://github.com/phil65/mknodes/blob/main/mknodes/basenodes/mklink/__init__.py)
### A simple Link (with optional icon and option to show up as a button).
!!! info "Description"
If no title is given, the URL is used as a title.
=== "Examples"
### Example: **Regular**
!!! jinja "Jinja"
``` {.jinja }
{{ "https://www.google.com" | MkLink("This is a link") }}
```
!!! python "Python"
``` {.python }
MkLink('https://www.google.com', 'This is a link')
```
===! "Rendered"
[This is a link](https://www.google.com)
=== "Markdown"
``` {.markdown }
[This is a link](https://www.google.com)
```
=== "Html"
``` {.html }
|
=== "⋔ Inheritance diagram"
``` mermaid
graph TD
94420313452496["mklink.MkLink"]
94420313076768["mknode.MkNode"]
94420313236736["node.Node"]
140608527347936["builtins.object"]
94420313076768 --> 94420313452496
94420313236736 --> 94420313076768
140608527347936 --> 94420313236736
```
=== "NodeFile"
``` {.toml title='/home/runner/work/mknodes/mknodes/mknodes/basenodes/mklink/metadata.toml'}
[metadata]
icon = "octicon:link-24"
name = "MkLink"
[examples.regular]
title = "Regular"
jinja = """
{{ "https://www.google.com" | MkLink("This is a link") }}
"""
[examples.button]
title = "Button"
jinja = """
{{ "https://www.google.com" | MkLink("Disguised as button.", as_button=True) }}
"""
[examples.colored]
title = "Colored"
jinja = """
{{ "https://www.google.com" | MkLink("Colored.", as_button=True, primary_color=True) }}
"""
[examples.with_icon]
title = "With icon"
jinja = """
{{ "https://www.google.com" | MkLink("With icon.", icon="octicon:link-24") }}
"""
[examples.with_tooltip]
title = "With tooltip"
jinja = """
{{ "https://www.google.com" | MkLink("With tooltip.", as_button=True) }}
"""
# [examples.to_page]
# title = "To Page"
# jinja = """
# {{ page.parent.index_page | MkLink("To page.") }}
# """
[output.markdown]
template = """
[{{ node.icon | add(suffix=" ") }}{{ node.title }}]({{ node.url }}{{ node.tooltip | add(prefix=" '", suffix="'")}})
"""
[output.rst]
template = """
`{{ node.title }} <{{ node.url }}>`_
"""
```
=== "Code"
``` {.python title='mknodes.basenodes.mklink.MkLink' linenums='19'}
class MkLink(mknode.MkNode):
"""A simple Link (with optional icon and option to show up as a button).
If no title is given, the URL is used as a title.
"""
ICON = "octicons/link-24"
ATTR_LIST_SEPARATOR = ""
def __init__(
self,
target: linkprovider.LinkableType,
title: str | None = None,
*,
tooltip: str | None = None,
icon: str | None = None,
as_button: bool = False,
primary_color: bool = False,
**kwargs: Any,
):
"""Constructor.
Args:
target: Link target
title: Title used for link
tooltip: Tooltip for the link
icon: Optional icon to be displayed in front of title
as_button: Whether link should be rendered as button
primary_color: If rendered as button, use primary color as background.
kwargs: keyword arguments passed to parent
"""
super().__init__(**kwargs)
self.target = target
self._title = title
self.tooltip = tooltip
self.as_button = as_button
self.primary_color = primary_color
self._icon = icon
if as_button:
self.add_css_class("md-button")
if primary_color:
self.add_css_class("md-button--primary")
@property
def icon(self) -> str:
return icons.get_emoji_slug(self._icon) if self._icon else ""
@property
def url(self) -> str:
return self.ctx.links.get_url(self.target)
@property
def title(self) -> str:
return self._title or self.url
@classmethod
def for_pydantic_playground(
cls,
files: Mapping[str, str]
| list[types.ModuleType]
| Sequence[str | os.PathLike[str]],
title: str = "Open in Pydantic Playground",
active_index: int = 0,
**kwargs: Any,
) -> MkLink:
"""Create a link to Pydantic playground with pre-populated files.
Args:
files: The files to include in the playground. Can be:
- A mapping of filenames to code content
- A list of modules
- A list of file paths
title: The title of the link
active_index: The index of the active file in the playground
**kwargs: Additional keyword arguments to pass to the Pydantic playground
Returns:
An MkLink instance pointing to the Pydantic playground
"""
from urllib.parse import quote
match files:
case Mapping():
file_data: list[dict[str, Any]] = [
{"name": name, "content": content} for name, content in files.items()
]
case [types.ModuleType(), *_]:
file_data = [
{"name": f"{mod.__name__}.py", "content": inspect.getsource(mod)} # type: ignore
for mod in files
]
case [str() | os.PathLike(), *_]:
file_data = []
for path in files:
file = upath.UPath(path)
file_data.append({
"name": file.name,
"content": file.read_text("utf-8"),
})
case _:
raise TypeError(files)
# Add activeIndex to first file
if file_data:
file_data[active_index]["activeIndex"] = 1
json_str = json.dumps(file_data)
encoded = quote(json_str)
url = f"https://pydantic.run/new?files={encoded}"
return cls(url, title, **kwargs)
def _to_markdown(self) -> str:
prefix = f"{self.icon} " if self.icon else ""
tooltip = f" {self.tooltip!r}" if self.tooltip else ""
return f"[{prefix}{self.title}]({self.url}{tooltip})"
```